package com.weike.wk_android.view.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.material.tabs.TabLayout;
import com.trello.rxlifecycle3.components.support.RxFragment;
import com.weike.wk_android.R;
import com.weike.wk_android.model.InformationTab;
import com.weike.wk_android.widget.adapter.TabPagerAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 资讯页面
 */
public class InformationFragment extends RxFragment {
    @BindView(R.id.information_content)
    ViewPager informationContent;
    @BindView(R.id.information_tab)
    TabLayout informationTab;

    private Unbinder unbinder;
    private View root;
    private boolean lazyload;
    private TabPagerAdapter tpAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (root == null) {
            root = inflater.inflate(R.layout.fragment_information, container, false);
        }

        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, root);

//        if (lazyload) {
            initView();
//        }

        // 缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) root.getParent();
        if (parent != null) {
            parent.removeView(root);
        }

        return root;
    }

    /**
     * 初始化数据
     */
    private void initView() {
        initTabLayout();
        initViewPager();

        lazyload = true;
    }

    /**
     * 获取ViewPager数据
     */
    private void initViewPager() {
        // 设置ViewPager的适配器
        tpAdapter = new TabPagerAdapter(getFragmentManager());
        informationContent.setAdapter(tpAdapter);

        // 设置TabLaout和ViewPager联动
        informationTab.setupWithViewPager(informationContent);
    }

    /**
     * 初始化TabSpc
     */
    private void initTabLayout() {
        String[] tab_txt = InformationTab.getTabsTxt();

        for (String txt: tab_txt) {
            informationTab.addTab(informationTab.newTab().setText(txt));
        }
    }

    @Override
    public void onDestroyView() {
        // 解除绑定
        if (unbinder != null) {
            unbinder.unbind();
        }

        super.onDestroyView();
    }
}
